package com.handpay.zztong.hp.download.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.Volley;
import com.handpay.framework.SSLCustomSocketFactory;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.ZZTApplication;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.permission.PermissionRequestCode;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

/**
 * @author yanglun E-mail:sunshine_yangl@sina.com
 * @version 2015-12-2 下午2:36:03
 */
public class DownloadApkActivity extends ZZTongActivity {

    private WebView webview;
    private ProgressBar update_apk_progressbar;
    private String url, downloadUrl, filePath;
    private RelativeLayout download_content_rl;
    private Handler mHandler;
    private Message msg;
    private TextView update_apk_percent_tv;
    public static final int MSG_UNDOWN = 0; // 未开始下载
    public static final int MSG_DOWNING = 1; // 下载中
    public static final int MSG_FINISH = 2; // 下载完成
    public static final int MSG_FAILURE = 3;// 下载失败
    private long time = System.currentTimeMillis();
    private Response.Listener<String> successListener;
    private Response.ErrorListener errorListener;
    private String APP_FOLDER = "/zzTong/apk";
    private String FILE_NAME = "zzt.apk";


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        this.setContentView(R.layout.activity_download_apk);
        super.onCreate(savedInstanceState);
        webview = (WebView) this.findViewById(R.id.download_webview);
        download_content_rl = (RelativeLayout) this.findViewById(R.id.download_content_rl);
        update_apk_progressbar = (ProgressBar) this.findViewById(R.id.update_apk_progressbar);
        update_apk_percent_tv = (TextView) this.findViewById(R.id.update_apk_percent_tv);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_DOWNING: {
                        int progress = msg.arg1;
                        update_apk_progressbar.setProgress(progress);
                        update_apk_percent_tv.setText(progress + "%");
                        break;

                    }
                    case MSG_FINISH: {
                        String filePath = (String) msg.obj;
                        openFile(new File(filePath));
                        ZZTApplication.getApp().exitApp();
                        break;
                    }
                    case MSG_FAILURE: {
                        ZZTApplication.getApp().exitApp();
                        break;
                    }
                    default:
                        break;
                }

            }
        };
        OnTouchListener onTouchListener = new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        };
        download_content_rl.setOnTouchListener(onTouchListener);
        webview.getSettings().setJavaScriptEnabled(true);
        url = this.getIntent().getStringExtra(UPDATEURL);
        webview.loadUrl(url);
        webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                String testUrl = "https://down.handmart.cn/HXLikePay.apk";
//                String testUrl = "https://down.handmart.cn/HXLikePay.apk?version=2.3.6";

//                FILE_NAME = url.substring(url.lastIndexOf("/") + 1);

                File saveFile = createSDCardFile(APP_FOLDER + File.separator + FILE_NAME);
                filePath = saveFile.getPath();
                HPLog.i(HPLog.YL_TAG, "filePath:" + filePath);
                if (url.contains(".apk")) {
                    downloadUrl = url;
                    downloadApkWithHttpUrlConn();
                }
                view.loadUrl(url);
                return true;
            }
        });

        if (ZZTConfig.isUseHTTPS) {
            //双向认证
            InputStream p12Keystore = getResources().openRawResource(R.raw.sandpayclient_hpd);
            InputStream trustKeyStore = getResources().openRawResource(R.raw.sandpayserver_hpd);
            requestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, SSLCustomSocketFactory.getSocketFactory(p12Keystore, "1234567890", trustKeyStore)));
            //单项认证
            //InputStream trustKeyStore = getResources().openRawResource(R.raw.handpayssl);
            //requestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, SSLCustomSocketFactory.getSocketFactory(trustKeyStore, "handpay")));
        } else {
            requestQueue = Volley.newRequestQueue(this);
        }
//        initPermission();
    }

    /**
     * 获取权限
     */
    private void checkPermission() {
        HPLog.i(HPLog.YL_TAG, "checkPermission RequestCode:" + PermissionRequestCode.REQUEST_CODE_PERMISSION_READ_PHONE_STATE_AND_STORAGE);
        AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_PERMISSION_READ_PHONE_STATE_AND_STORAGE).
                permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE).
                rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(DownloadApkActivity.this, rationale).show();
                    }
                }).send();
    }

    @Override
    public void onSucceed(int requestCode, List<String> grantPermissions) {
        if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_READ_PHONE_STATE_AND_STORAGE) {
            download_content_rl.setVisibility(View.VISIBLE);
            new ApkFileDownload(DownloadApkActivity.this, mHandler, downloadUrl, filePath).start();
        }
    }

    /***
     * @para
     */
    private void downloadApkWithHttpUrlConn() {
        checkPermission();
    }

    public File createSDCardFile(String fileName) {
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


//
//	private static String[] PERMISSIONS_STORAGE = {
//			android.Manifest.permission.READ_EXTERNAL_STORAGE,
//			android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
//
//	public static void verifyStoragePermissions(Activity activity) {
//		// Check if we have write permission
//		int permission = ActivityCompat.checkSelfPermission(activity,
//				android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
//
//		if (permission != PackageManager.PERMISSION_GRANTED) {
//			// We don't have permission so prompt the user
//			ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
//					REQUEST_EXTERNAL_STORAGE);
//		}
//	}


    @Override

    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.download_apk_title), false);
    }

    public class ApkFileDownload extends Thread {
        private Context mContext;
        private Handler mHandler;
        private String mDownloadUrl; // 文件下载url，已做非空检查
        private String mFileName;
        private Message msg;

//        private final String APP_FOLDER = "ZZTongActivity"; // sd卡应用目录
//        private final String APK_FOLDER = "download"; // 下载apk文件目录

        public ApkFileDownload(Context context, Handler handler, String downloadUrl, String fileName) {
            mContext = context;
            mHandler = handler;
            mDownloadUrl = downloadUrl;
            mFileName = fileName;
        }

        public void run() {
            try {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    msg = mHandler.obtainMessage();
                    msg.what = MSG_DOWNING;
                    mHandler.sendMessage(msg);
                    // SD卡准备好
//                    File sdcardDir = Environment.getExternalStorageDirectory();
//                    File saveFile = new File(sdcardDir + File.separator + APP_FOLDER + File.separator + APK_FOLDER, mFileName);
                    File saveFile = new File(mFileName);

                    if (!saveFile.getParentFile().exists()) {
                        saveFile.getParentFile().mkdirs();
                    }
                    if (saveFile.exists()) {
                        saveFile.delete();
                        saveFile.createNewFile();
                    }
                    boolean downSuc;
                    if (mDownloadUrl.startsWith("https://"))
                        downSuc = downloadFileWithHttps(mDownloadUrl, saveFile);
                    else
                        downSuc = downloadFileWithHttp(mDownloadUrl, saveFile);
                    if (downSuc) {
                        msg = mHandler.obtainMessage();
                        msg.what = MSG_FINISH;
                        msg.obj = saveFile.getPath();

                    } else {
                        msg = mHandler.obtainMessage();
                        msg.what = MSG_FAILURE;

                    }

                } else {
                    Toast.makeText(mContext, Environment.getExternalStorageState(), Toast.LENGTH_SHORT).show();
                    msg.what = MSG_FAILURE;
                }
            } catch (Exception e) {

                msg.what = MSG_FAILURE;
            } finally {
                mHandler.sendMessage(msg);
            }
        }

        /**
         * Desc:文件下载
         *
         * @param downloadUrl  下载URL
         * @param saveFilePath 保存文件路径
         * @return ture:下载成功 false:下载失败
         */
        public boolean downloadFileWithHttps(String downloadUrl, File saveFilePath) {
            int fileSize = -1;
            int downFileSize = 0;
            boolean result = false;
            int progress = 0;
            try {
                // 创建SSLContext对象，并使用我们指定的信任管理器初始化
                InputStream keyStore = getResources().openRawResource(R.raw.handpaydownlad);
                URL url = new URL(downloadUrl);
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                httpsURLConnection.setSSLSocketFactory(SSLCustomSocketFactory.getSocketFactory(keyStore, "handpay"));
                // 读取超时时间 毫秒级
                httpsURLConnection.setReadTimeout(10000);
                httpsURLConnection.setRequestMethod("GET");
                httpsURLConnection.setDoInput(true);
                httpsURLConnection.connect();
                if (httpsURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    fileSize = httpsURLConnection.getContentLength();
                    InputStream is = httpsURLConnection.getInputStream();
                    FileOutputStream fos = new FileOutputStream(saveFilePath);
                    byte[] buffer = new byte[1024];
                    int i = 0;
                    int tempProgress = -1;
                    long time = System.currentTimeMillis();
                    while ((i = is.read(buffer)) != -1) {
                        downFileSize = downFileSize + i;
                        // 下载进度
                        progress = (int) (downFileSize * 100.0 / fileSize);
                        fos.write(buffer, 0, i);

                        synchronized (this) {
                            if (downFileSize == fileSize) {
                                // 下载完成
                                // mNotifManager.cancel(R.id.downLoadIcon);
                            } else if (tempProgress != progress) {

                                long curTime = System.currentTimeMillis();
                                if (curTime - time > 1000) {
                                    msg = mHandler.obtainMessage();
                                    msg.what = MSG_DOWNING;
                                    msg.arg1 = progress;
                                    mHandler.sendMessage(msg);
                                }

                                tempProgress = progress;
                            }
                        }
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                result = false;
            }
            return result;
        }

        /**
         * Desc:文件下载
         *
         * @param downloadUrl  下载URL
         * @param saveFilePath 保存文件路径
         * @return ture:下载成功 false:下载失败
         */
        public boolean downloadFileWithHttp(String downloadUrl, File saveFilePath) {
            int fileSize = -1;
            int downFileSize = 0;
            boolean result = false;
            int progress = 0;
            try {
                URL url = new URL(downloadUrl);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                if (null == httpURLConnection) {
                    return false;
                }
                // 读取超时时间 毫秒级
                httpURLConnection.setReadTimeout(10000);
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setDoInput(true);
                httpURLConnection.connect();
                if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    fileSize = httpURLConnection.getContentLength();
                    InputStream is = httpURLConnection.getInputStream();
                    FileOutputStream fos = new FileOutputStream(saveFilePath);
                    byte[] buffer = new byte[1024];
                    int i = 0;
                    int tempProgress = -1;
                    long time = System.currentTimeMillis();
                    while ((i = is.read(buffer)) != -1) {
                        downFileSize = downFileSize + i;
                        // 下载进度
                        progress = (int) (downFileSize * 100.0 / fileSize);
                        fos.write(buffer, 0, i);

                        synchronized (this) {
                            if (downFileSize == fileSize) {
                                // 下载完成
                                // mNotifManager.cancel(R.id.downLoadIcon);
                            } else if (tempProgress != progress) {

                                long curTime = System.currentTimeMillis();
                                if (curTime - time > 1000) {
                                    msg = mHandler.obtainMessage();
                                    msg.what = MSG_DOWNING;
                                    msg.arg1 = progress;
                                    mHandler.sendMessage(msg);
                                }

                                tempProgress = progress;
                            }
                        }
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                result = false;
                // Log.e(AhzyFisActivity.TAG, "downloadFileWithHttps catch Exception:",
                // e);
            }
            return result;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void openFile(File file) {
        showProgressDialog(this, getString(R.string.tip), getString(R.string.detech_apk), false);
//        boolean flag = detechapk(file.getAbsolutePath());
        boolean flag = true;
        closeProgressDialog();
        if (flag) {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            startActivity(intent);
        } else {
            showAlertDialog(this, getString(R.string.tip), getString(R.string.sigtrue_fail), true, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    goBack();
                    dialog.dismiss();
                }
            });
        }

    }

    //2016-11-16新增
    private boolean detechapk(String path) {
        try {
            String apkpath = Environment.getExternalStorageDirectory().getAbsolutePath();
            File fe = new File(apkpath);
            if (fe.exists()) {
                Signature downapksingtrue = CommonUtils.getNoInstalledApkSignature(path);
                Signature myapk = CommonUtils.getInstallPackageSignature(this, this.getPackageName());
                if (downapksingtrue != null) {
                    String m = CommonUtils.getMD5(downapksingtrue);
                    String m1 = CommonUtils.getMD5(myapk);
                    String s = CommonUtils.getSHA1(downapksingtrue);
                    String s1 = CommonUtils.getSHA1(myapk);
                    if (m.trim().equalsIgnoreCase(m1) && s.equalsIgnoreCase(s1)) {
                        return true;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }
}
